﻿using DemoApp2.Common;
using DemoApp2.Models;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Security;

namespace DemoApp2
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AppConfig.Configure();
        }

        public override void Init()
        {
            this.AuthenticateRequest += MvcApplication_AuthenticationRquest;
            base.Init();
        }

        void MvcApplication_AuthenticationRquest(object sender, EventArgs e)
        {
            string requestUrl = HttpContext.Current.Request.RawUrl;
            HttpCookie accessTokenCookie = null;
            //非AJAX请求 AccessToken
            if (!new HttpContextWrapper(Context).Request.IsAjaxRequest())
            {
                accessTokenCookie = HttpContext.Current.Request.Cookies[AppConfig.AccessTokenCookieName];
            }
            else
            { //RefreshToken
                accessTokenCookie = HttpContext.Current.Request.Cookies[AppConfig.RefreshedAccessTokenCookieName];
            }
            if (accessTokenCookie != null)
            {
                var decryptedAccessTokenTicket = FormsAuthentication.Decrypt(accessTokenCookie.Value);
                if (decryptedAccessTokenTicket != null)
                {
                    var accessToken = decryptedAccessTokenTicket.UserData;
                    RestClientHelp restClientHelp = new RestClientHelp(AppConfig.AuthorizationServerBaseAddress, AppConfig.ResourceServerAPIAddress);

                    //获取用户信息
                    string result = restClientHelp.GetUserData(accessToken);
                    if (!string.IsNullOrWhiteSpace(result) && string.Compare(result, "null", true) != 0)
                    {
                        dynamic user = JObject.Parse(result);
                        string userName = user.Name;
                        string userRoles = user.RoleNames;
                        string[] roles = userRoles.Split(',');
                        //AjAX 请求
                        if (new HttpContextWrapper(Context).Request.IsAjaxRequest())
                        {
                            string authenticatedUserName = HttpContext.Current.Request.Headers.Get(AppConfig.HeaderNameForAjaxAuth);
                            userName = string.Compare(userName, authenticatedUserName, true) == 0 ? userName : null;
                        }
                        if (!string.IsNullOrWhiteSpace(userName))
                        {
                            var claims = new List<Claim>();
                            claims.Add(new Claim(ClaimTypes.Name, userName));

                            var identity = new ClaimsIdentity(claims, AppConfig.ClientId + "_FormAuthentication");
                            ClaimsPrincipal principal = new GenericPrincipal(identity, roles);
                            HttpContext.Current.User = principal;
                        }
                    }
                    if (!new HttpContextWrapper(Context).Request.IsAjaxRequest())
                    {
                        accessTokenCookie.Expires = DateTime.Now.AddDays(-1);
                        HttpContext.Current.Response.Cookies.Add(accessTokenCookie);
                    }
                }
            }
        }
    }
}
